import { useAppStore } from '@/store';
import { getCurrentPermissionList } from '@/api/setting';
import routers from '@/router';
import { Message } from '@arco-design/web-vue';
import { useRouter } from 'vue-router';

const router = useRouter();
function resolveComponent(name: string) {
  const modules = import.meta.glob('@/views/**/**/*.vue');
  const importPage = modules[`${name}`] as any;
  if (!importPage) {
    console.warn(`Page not found: ${name}`);
    // Message.error(`Page not found: ${name}`);
    // routers.push({name:'login'});
    // throw new Error(`Unknown page: ${name}`);
  }
  return importPage;
}

export async function initRouterNode(reload: boolean = false) {
  let menuTree: any = [];
  const appStore: any = useAppStore();
  console.log('获取菜单', appStore.appRoute);
  if (!appStore.appRoute.length || reload) {
    const res = await getCurrentPermissionList();
    menuTree = res.data.result;
  } else {
    menuTree = appStore.appRoute;
  }
  const data: any = menuTree;
  appStore.updateRoute(menuTree);
  data.forEach((item: any) => {
    // 判断当前router是否已经存在，如果存在则不添加
    routers.addRoute({
      name: item.name,
      path: `/${item.path}`,
      component: () => import('@/layout/default-layout.vue'),
      children: item.children.map((child: any) => {
        return {
          name: child.name,
          path: `/${child.path}`,
          component: resolveComponent(`/src/${child.frontRoute}.vue`),
        };
      }),
    });
  });
}
